<template>
  <div class="departments">
    <el-card class="box-card">
      <template #header>
        <span>组织架构</span>
      </template>
      <div class="other-content">
        <tree-item :item="topInfo" :is-top="true" />
        <hr>
        <el-tree :data="treeData" :props="{ label: 'name' }">
          <template v-slot="{ data }">
            <tree-item :item="data" style="width: 100%" @getDep="getDep" />
          </template>
        </el-tree>
      </div>
    </el-card>
    <Add :init-list="initList" />
  </div>
</template>

<script>
import TreeItem from './components/treeItem.vue'
import Add from './components/Add.vue'
import { companyDepartment } from '@/api/departments'
export default {
  components: {
    TreeItem,
    Add
  },
  data() {
    return {
      initList: [],
      isTop: true, // 是否顶部数据
      topInfo: {
        name: '传智播客',
        manager: '负责人',
        id: ''
      },
      // 部门树形结构
      treeData: [
        {
          name: '事业部',
          manager: '孙财',
          children: [
            {
              name: '北京事业部'
            }
          ]
        }
      ]
    }
  },
  created() {
    this.getDep()
  },
  methods: {
    // 封装获取部门列表函数
    async getDep() {
      const res = await companyDepartment()
      // console.log(res)
      this.topInfo.name = res.data.companyName // 修改顶部信息
      this.topInfo.manager = res.data.companyManager // 修改顶部信息
      this.treeData = this.treeDep(res.data.depts, '')
      this.initList = res.data.depts
    },
    // 定义递归函数,获取部门树形结构
    treeDep(arr, pid = '') {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.treeDep(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 15px;
  .other-content {
    padding: 40px 100px;
  }
}
</style>
